﻿using System;
using System.Collections.Generic;
using System.IO;
using Windows.UI.Xaml.Media.Imaging;
using System.Linq;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Input;
using Windows.UI.Core;
using System.Threading;
using System.Collections.Concurrent;

namespace RoboRun
{
    /// <summary>
    /// For purposes of demo, 3x3 grid is used.
    /// </summary>
    public sealed partial class GameplayScreen : Page
    {
        public static float width;
        public static float height;
        public static float offset = 0; //Use this when doing margins. Offset required for 16:10 displays.

        public static bool trueIs16By9FalseIs16By10; //Just for reference. Probably won't be used.

        //Level Information
        public static String GridType = "3x3";
        public static String RobotStartingPosition = "3,1"; //Row, Column
        public static String RobotStartingDirection = "North"; //First letter must be uppercase, rest lower
        public static String GoalPosition = "3,3"; //MUST NOT BE THE SAME AS STARTING POSITION!
        //public static String LevelNumber; 

        public static String[] ObstaclePositions;//Length of array dictates how many obstacles

        public static Image Obstacle1;

        public static bool playPressed = false;
        private Timer timer;
        private static int ticks;

        public static TextBlock score;

        public static Image RobotSpriteRef; //reference used to manipulate robot sprite.
        public static String RobotCurrentDirection;
        public static String RobotCurrentPosition;

        public static String commandExecuted = ""; //logs what command has just been done by the user. adds to queue later on.
        public static TextBox debugger; //for debugging purposes, remove when done
        public static TextBlock adviceBox;

        public static Image hintBox;
        public static Image hintText;

        //assets for game over screen. these are needed because i am calling these assets from another class. instantiating a gameplayscreen object and calling a method from here doesn't work.

        public static Image BlackOverlayGameOver;
       
        public static Image RedBlockGameOver;
        public static Image TextPromptGameOver;
        public static Button PromptForwardGameOver;
        public static Button PromptBackGameOver;
        public static Viewbox ForwardViewBoxGameOver;
        public static Viewbox BackViewBoxGameOver;
        public static Image touchDevelop;
        public static Image touchDevelopText;

        public static Image confirmLabelGameOver;
        public static Image exitLabelGameOver;

        public static Image forButtonStatic;
        public static Image whileButtonStatic;
        public static Image ifButtonStatic;

        public static Image playLabelStatic;
        public static Image undoLabelStatic;



        public GameplayScreen()
        {
            this.InitializeComponent();
            Layout obj = new Layout();
            makeStaticReferenceToRobotSprite();
            debugger = debug;
            RobotCurrentDirection = RobotStartingDirection;
            RobotCurrentPosition = RobotStartingPosition;
            obtainScreenDimensions();
            determineAspectRatio();
            loadObstacleSprite();
            makeStaticReferenceToLabels();
            makeStaticReferenceToGameOverAssets();
            makeStaticReferenceToControlImages();
            touchDevelop = TouchDevelopButton;
            touchDevelopText = TouchDevelopText;
            //adviceBox = adviceBoxBlock;
            timer = new Timer();
            timer.setupTimer();
            hintBox = HintBar;
            score = Score;
            hintText = HintAdvice;
            obj.loadCommandsTitle(CommandsTitle,width,height,offset); //fine
            obj.loadControlsTitle(ControlsTitle, width, height, offset); //fine
            obj.loadGoal(Goal, GridType);//need to specify goal size based on grid size
            obj.loadGoStraightButton(GoStraightButtonImage,GoStraightButton,width,height,offset); //fine
            obj.loadTurnLeftbutton(TurnLeftButtonImage, TurnLeftButton, width, height, offset); //fine
            obj.loadTurnRightButton(TurnRightButtonImage, TurnRightButton, width, height, offset); //fine
            obj.loadIfButton(IfButtonImage, IfButton); //fine
            obj.loadForButton(ForButtonImage, ForButton); //fine
            obj.loadLabels(playLabelStatic,undoLabelStatic, width,height,offset);
            obj.loadWhileButton(WhileButtonImage, WhileButton); //fine
            obj.loadRobotSprite(RobotSprite, width, height, offset, GridType, RobotStartingDirection, RobotStartingPosition); //based on grid size
            obj.loadPlayButton(PlayButtonImage, width, height, offset); //fine
            obj.loadUndoButton(UndoButtonImage); //fine
            obj.setUpCommandQueueTextBox(commandQueueScrollViewer,commandQueueTextBlock,height,width,offset); //fine
        }

        private void makeStaticReferenceToLabels()
        {
            playLabelStatic = playLabel;
            undoLabelStatic = undoLabel;
        }

        private void makeStaticReferenceToGameOverAssets() //needed when game over is called
        {
            BlackOverlayGameOver = BlackOverlay;
            RedBlockGameOver = RedBlock;
            TextPromptGameOver = TextPrompt;
            confirmLabelGameOver = confirmLabel;
            exitLabelGameOver = exitLabel;
            ForwardViewBoxGameOver = ForwardViewBox;
            BackViewBoxGameOver = BackViewBox;
            PromptBackGameOver = PromptBack;
            PromptForwardGameOver = PromptForward;
        }

        public static void gameOverEndOfQueue()
        {
            Prompt.showBlackOverlay(BlackOverlayGameOver, GameplayScreen.width, GameplayScreen.height, GameplayScreen.offset);
            Prompt.showRedBlockGameOver(RedBlockGameOver, GameplayScreen.width, GameplayScreen.height, GameplayScreen.offset, TextPromptGameOver, PromptBackGameOver, PromptForwardGameOver, BackViewBoxGameOver, ForwardViewBoxGameOver, confirmLabelGameOver, exitLabelGameOver);
        }

        private void makeStaticReferenceToRobotSprite()
        {
            RobotSpriteRef = RobotSprite;
        }

        private void makeStaticReferenceToControlImages()
        {
            forButtonStatic = ForButtonImage;
            whileButtonStatic = WhileButtonImage;
            ifButtonStatic = IfButtonImage;
        }

        private void determineAspectRatio()
        {
            if (width/height == 1.6) //implies 16:10 aspect ratio
            {
                offset = 40 * height / 800;
                trueIs16By9FalseIs16By10 = false;
            }
            else 
            {
                offset = 0;
                trueIs16By9FalseIs16By10 = true;
            }
            Layout.loadLayout(CommandsBG,GridBG,ControlsBG,Grid,height,width,offset);
        }

        private void obtainScreenDimensions()
        {
            width = ScreenDimensions.obtainScreenWidth();
            height = ScreenDimensions.obtainScreenHeight();
        }

        public static Thickness robotSpriteMargin; //used and manipulated to move robot

        public void loadObstacleSprite() //need to add case for 3x3, 4x4 etc.
        {
            if (GridType.Equals("3x3"))
            {
                ThreeXThreeObstacles();
            }
            else if (GridType.Equals("4x4"))
            {
                FourXFourObstacles();
            }
        } //loads obstacles onto screen, can have up to 7 obstacles on a 3x3 grid

        private void FourXFourObstacles()
        {
            if (ObstaclePositions.Length != 0)
            {
                for (int i = 1; i <= ObstaclePositions.Length; i++)
                {
                    switch (i)
                    {
                        case 1:
                            ObstacleSprite1.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite1.Width = 300 * width / 1920;
                            ObstacleSprite1.Height = 300 * height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite1, ObstaclePositions[i - 1], offset);
                            break;
                        case 2:
                            ObstacleSprite2.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite2.Width = 300 * width / 1920;
                            ObstacleSprite2.Height = 300 * height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite2, ObstaclePositions[i - 1], offset);
                            break;
                        case 3:
                            ObstacleSprite3.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite3.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite3.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite3, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 4:
                            ObstacleSprite4.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite4.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite4.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite4, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 5:
                            ObstacleSprite5.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite5.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite5.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite5, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 6:
                            ObstacleSprite6.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite6.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite6.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite6, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 7:
                            ObstacleSprite7.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/4X4Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite7.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite7.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition4x4(ObstacleSprite7, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                    }
                }
                Obstacle1 = ObstacleSprite1;
            }
        }

        private void ThreeXThreeObstacles()
        {
            if (ObstaclePositions.Length != 0)
            {
                for (int i = 1; i <= ObstaclePositions.Length; i++)
                {
                    switch (i)
                    {
                        case 1:
                            ObstacleSprite1.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite1.Width = 300 * width / 1920;
                            ObstacleSprite1.Height = 300 * height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite1, ObstaclePositions[i - 1], offset);
                            break;
                        case 2:
                            ObstacleSprite2.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite2.Width = 300 * width / 1920;
                            ObstacleSprite2.Height = 300 * height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite2, ObstaclePositions[i - 1], offset);
                            break;
                        case 3:
                            ObstacleSprite3.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite3.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite3.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite3, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 4:
                            ObstacleSprite4.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite4.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite4.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite4, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 5:
                            ObstacleSprite5.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite5.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite5.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite5, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 6:
                            ObstacleSprite6.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite6.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite6.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite6, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                        case 7:
                            ObstacleSprite7.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/3X3Grid/obstacle.png", UriKind.Absolute
                      ));
                            ObstacleSprite7.Width = 300 * GameplayScreen.width / 1920;
                            ObstacleSprite7.Height = 300 * GameplayScreen.height / 1080;
                            drawInPosition.drawInPosition3x3(ObstacleSprite7, ObstaclePositions[i - 1], GameplayScreen.offset);
                            break;
                    }
                }
                Obstacle1 = ObstacleSprite1;
            }
        }

        private void GoStraightButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (commandExecuted.Contains("If Statement"))
            {
                commandExecuted = ("If Statement Go Straight");
            }
            else
            {
                commandExecuted = "Go Straight";
            }
            GoStraightButton.IsEnabled = false;
            showGoStraightPopUp();
            disableAllButtons();
        }

        private void TurnLeftButton_Click_1(object sender, RoutedEventArgs e)
        {
            debugger.Text = commandExecuted;
            if (commandExecuted.Contains("If Statement")) //if any control statement is used
            {
                commandExecuted = "If Statement Turn Left";
                
            }
            else
            {
                commandExecuted = "Rotate Anti-Clockwise";
            }
            TurnLeftButton.IsEnabled = false;
            addTurnLeftToQueue();
            ButtonFlash.buttonFlash(TurnLeftButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/turnleftbuttoninverted.png", UriKind.Absolute),
                new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/turnleftbutton.png"));
            commandQueueScrollViewer.UpdateLayout();
            commandQueueScrollViewer.ScrollToVerticalOffset(commandQueueScrollViewer.ActualHeight);
        }

        private void TurnRightButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (commandExecuted.Contains("If Statement")) //if any control statement is used
            {
                commandExecuted = "If Statement Turn Right";
                debugger.Text = commandExecuted;
            }
            else
            {
                commandExecuted = "Turn Right";
                debugger.Text = commandExecuted;
            }
            TurnRightButton.IsEnabled = true;
            ButtonFlash.buttonFlash(TurnRightButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/turnrightbuttoninverted.png", UriKind.Absolute),
                new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/turnrightbutton.png"));
            addTurnRightToQueue();
            commandQueueScrollViewer.UpdateLayout();
            commandQueueScrollViewer.ScrollToVerticalOffset(commandQueueScrollViewer.ActualHeight);
        }

        public static bool elseMarker = false; //marker used to distinguish between if and else clauses in the if statement

        private void IfButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (elseMarker == true)
            {
                debugger.Text = "END ELSE CLAUSE";
                elseMarker = false;
                commandExecuted = "";
                IfButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/ifbutton.png", UriKind.Absolute
                      ));
                ForButton.IsEnabled = true;
                WhileButton.IsEnabled = true;
            }
            else if (commandExecuted.Contains("If Statement"))
            {
                ForButton.IsEnabled = false;
                WhileButton.IsEnabled = false;
                elseMarker = true;
                if (formarker == true||whilemarker==true)
                {
                    CommandQueue.addToCommandQueue("   Else:", commandQueueTextBlock, commandQueueScrollViewer);
                }
                else
                {
                    CommandQueue.addToCommandQueue("Else:", commandQueueTextBlock, commandQueueScrollViewer);
                }
                
                IfButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/finishbutton.png", UriKind.Absolute
                      ));

            }
            else
            {
                commandExecuted = "If Statement";
                ButtonFlash.buttonFlash(IfButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/ifbuttoninverted.png", UriKind.Absolute),
                new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/ifbutton.png"));
                IfButton.IsEnabled = false;
                startIfPrompt();
                disableAllButtons();
            }
        }

        private void startIfPrompt()
        {
            Prompt.showBlackOverlay(BlackOverlay, width, height, offset);
            Prompt.showRedBlockIfStatement(RedBlock, PromptBack, PromptForward, BackViewBox, ForwardViewBox, confirmLabel, exitLabel,IfTitle, IfPrompt1st, IfPrompt2nd, IfStatementComboBox, IfTextEntry);
        }

        private void addTurnLeftToQueue()
        {
            if (commandExecuted.Contains("If Statement"))
            {
                CommandQueue.addToCommandQueue("\tRotate Anti-Clockwise", commandQueueTextBlock, commandQueueScrollViewer);
            }
            else if (formarker == true || whilemarker==true)
            {
                CommandQueue.addToCommandQueue(("   " + "Rotate Anti-Clockwise"), commandQueueTextBlock, commandQueueScrollViewer);
            }
            else
            {
                commandCounter++;
                CommandQueue.addToCommandQueue((GameplayScreen.commandCounter + ". " + "Rotate Anti-Clockwise"), commandQueueTextBlock, commandQueueScrollViewer);
            }
            TurnLeftButton.IsEnabled = true;
            debugger.Text = "Turn left button is now enabled...";
        }

        private void addTurnRightToQueue()
        {
            if (commandExecuted.Contains("If Statement"))
            {
                CommandQueue.addToCommandQueue("\tRotate Clockwise", commandQueueTextBlock, commandQueueScrollViewer);
            }
            else if (formarker == true || whilemarker == true)
            {
                CommandQueue.addToCommandQueue(("   " + "Rotate Clockwise"), commandQueueTextBlock, commandQueueScrollViewer);
            }
            else
            {
                commandCounter++;
                CommandQueue.addToCommandQueue((GameplayScreen.commandCounter + ". " + "Rotate Clockwise"), commandQueueTextBlock, commandQueueScrollViewer);
            }
            TurnRightButton.IsEnabled = true;
        }

        public static void gameOverPrompt()
        {
            debugger.Text = "Method successfully called";
            Prompt.showBlackOverlay(BlackOverlayGameOver, width, height, offset);
            Prompt.showRedBlockGameOver(RedBlockGameOver, width, height, offset, TextPromptGameOver, PromptBackGameOver, PromptForwardGameOver, BackViewBoxGameOver, ForwardViewBoxGameOver, confirmLabelGameOver, exitLabelGameOver);

        }

        public async static void playerWon()
        {
            debugger.Text = "YOU WIN!";
            Prompt.showBlackOverlay(BlackOverlayGameOver, width, height, offset);
            Prompt.showRedBlockYouWin(RedBlockGameOver, width, height, offset, TextPromptGameOver, PromptBackGameOver, PromptForwardGameOver, BackViewBoxGameOver, ForwardViewBoxGameOver, confirmLabelGameOver, exitLabelGameOver, touchDevelop, touchDevelopText);
            await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(1500));
            score.Opacity = 1;
            score.Height = 300*height/1080;
            score.Width = 700 * width / 1920;
            //score.Text = "Your score: 0000";
            score.FontSize = height / 15;
            score.FontWeight = Windows.UI.Text.FontWeights.SemiBold;
            score.Margin = new Thickness(1220*width/1920, offset + 25 * height / 1080, 0, 0);
            hintBox.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/Hints/hintbar.png", UriKind.Absolute
                                      ));
            hintBox.Height = 60 * height / 800;
            hintBox.Width = width;
            hintBox.Margin = new Thickness (0,715*height/800,0,0);
            hintAnimation();
           
        }

        private async static void hintAnimation()
        {
            hintText.Opacity = 1;
            hintText.Margin = new Thickness(hintText.Width, 715*height/800, 0, 0);
            double j = 0;
            while (j <=3250)
            {
                hintText.Margin = new Thickness(1900*width/1920 - j, 725 * height / 800, 0, 0);
                await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(7));
                j += 5;
            }
            double i = 1;
            while (i >= 0)
            {
                hintBox.Opacity = i;
                await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(20));
                i -= 0.1;
            }

            
        }


        private async void showGoStraightPopUp()
        {
            StraightTextEntry.IsReadOnly = true;
            ButtonFlash.buttonFlash(GoStraightButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/gostraightbuttoninverted.png", UriKind.Absolute
                  ), new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/gostraightbutton.png", UriKind.Absolute
                  ));
             await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(300));
             Prompt.showBlackOverlay(BlackOverlay,width,height,offset);
             Prompt.showRedBlock(RedBlock,width,height,offset,TextPrompt,PromptBack,PromptForward,BackViewBox,ForwardViewBox,confirmLabel,exitLabel, StraightTextEntry);
        }

        private void PromptBack_Click_1(object sender, RoutedEventArgs e)
        {
            if (commandExecuted.Contains("Player Won"))
            {
                commandQueue.Clear();
                commandCounter = 0;
                PrepareToPlay.userHasHitObstacleOrWall = false;
                this.Frame.Navigate(typeof(MainMenu)); //perhaps go to level select screen rather than main menu
            }
            else if (commandExecuted.Contains("Go Straight"))
            {
                Prompt.returnToGameplayFromPrompt(PromptBack, PromptForward, commandExecuted, StraightTextEntry, confirmLabel, exitLabel, TextPrompt, width, height, offset, RedBlock, BlackOverlay, GoStraightButton);
                enableAllButtons();
            }
            else if (commandExecuted.Equals("If Statement"))
            {
                Prompt.returnToGameplayFromPromptIfStatement(IfButton,PromptBack, PromptForward, commandExecuted, confirmLabel, exitLabel, RedBlock, BlackOverlay, IfTitle, IfPrompt1st,IfPrompt2nd,IfStatementComboBox,IfTextEntry);
                enableAllButtons();
            }
            else if (commandExecuted.Equals("For Loop"))
            {
                Prompt.returnToGameplayFromForLoop(ForButton, PromptBack, PromptForward, commandExecuted, confirmLabel, exitLabel, RedBlock, BlackOverlay, ForTitle, ForPrompt1st, ForPrompt2nd, ForTextEntry);
                enableAllButtons();
                formarker = false;
            }
            else if (commandExecuted.Equals("While Loop"))
            {
                Prompt.returnToGameplayFromWhileLoop(WhileButton, PromptBack, PromptForward, commandExecuted, confirmLabel, exitLabel, RedBlock, BlackOverlay, WhileTitle, WhilePrompt1st, WhilePrompt2nd, WhileLoopComboBox, WhileTextEntry);
                enableAllButtons();
                whilemarker = false;
            }
            else if (commandExecuted.Contains("Play"))
            {
                Prompt.returnToGameplayFromPrompt(PromptBack, PromptForward, commandExecuted, StraightTextEntry, confirmLabel, exitLabel, TextPrompt, width, height, offset, RedBlock, BlackOverlay, GoStraightButton);
                enableAllButtons();
            }
            else if (commandExecuted.Contains("Game Over"))
            {
                commandQueue.Clear();
                commandCounter = 0;
                GridType = null;
                ObstaclePositions = null;
                GoalPosition = null;
                PrepareToPlay.userHasHitObstacleOrWall = false;
                TouchDevelopCode.TDQueue.Clear();
                
                this.Frame.Navigate(typeof(MainMenu)); //will redraw level but not reset all data structures/counters/etc. above lines of code helps with that.
            }
            commandExecuted = "";
        }

        String goStraightEntry; //whatever the user enters into the box for go straight
        public static int commandCounter = 0;


        private void PromptForward_Click_1(object sender, RoutedEventArgs e)
        {
            if (commandExecuted.Contains("Game Over") || commandExecuted.Contains("Player Won")) //change at a later stage
            {
                // consider refactoring this into another method. this is here because putting into another method will be troublesome.
                commandQueue.Clear();
                commandCounter = 0;
                PrepareToPlay.userHasHitObstacleOrWall = false;
                Prompt.returnToGameplayFromPrompt(PromptBack, PromptForward, commandExecuted, StraightTextEntry, confirmLabel, exitLabel, TextPrompt, width, height, offset, RedBlock, BlackOverlay, GoStraightButton);
                this.Frame.Navigate(typeof(GameplayScreen)); //will redraw level but not reset all data structures/counters/etc. above lines of code helps with that.
            }

          

            else if (commandExecuted.Contains("Go Straight"))
            {
                Prompt.promptSubmission(commandExecuted, goStraightEntry, StraightTextEntry, PromptBack, PromptForward, confirmLabel, exitLabel, TextPrompt, width, height, offset, BlackOverlay, GoStraightButton, RedBlock, commandQueueTextBlock, commandQueueScrollViewer, Countdown);
                enableAllButtons();
            }
            else if (commandExecuted.Contains("Play"))
            {
                playPressed = true;
                setCurrentTimerTicks();
                score.Text = "Your Score = " + Scoring.getTotalScore().ToString();
                Scoring.printAdvice();
                Prompt.promptSubmission(commandExecuted, goStraightEntry, StraightTextEntry, PromptBack, PromptForward, confirmLabel, exitLabel, TextPrompt, width, height, offset, BlackOverlay, GoStraightButton, RedBlock, commandQueueTextBlock, commandQueueScrollViewer, Countdown);

            }
            else if (commandExecuted.Equals("If Statement"))
            {
                if (formarker == true || whilemarker == true)
                {
                    double num;
                    bool isNum = double.TryParse(IfTextEntry.Text, out num);
                    String check1 = (String)IfStatementComboBox.SelectedValue;

                    try
                    {
                        bool check = check1.Equals("");
                        if (isNum == true)
                        {
                            if (IfTextEntry.Text.Contains("0"))
                            {

                            }
                            else
                            {
                                CommandQueue.addToCommandQueue((("   If the robot is ") + (String)IfStatementComboBox.SelectedValue + " " + IfTextEntry.Text + " squares away from an obstacle:"), commandQueueTextBlock
                               , commandQueueScrollViewer);
                                Prompt.returnToGameplayFromPromptIfStatement(IfButton, PromptBack, PromptForward, null, confirmLabel, exitLabel, RedBlock, BlackOverlay, IfTitle, IfPrompt1st, IfPrompt2nd, IfStatementComboBox, IfTextEntry);
                                commandExecuted = "If Statement";
                                debugger.Text = commandExecuted;
                                IfButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/elsebutton.png", UriKind.Absolute
                                      ));
                                enableIfButtons();
                            }
                        }
                    }
                    catch (NullReferenceException)
                    {

                    }
                }
                else
                {
                    double num;
                    bool isNum = double.TryParse(IfTextEntry.Text, out num);
                    String check1 = (String)IfStatementComboBox.SelectedValue;
                    try
                    {
                        bool check = check1.Equals(null);
                        if (isNum == true)
                        {
                            if (IfTextEntry.Text.Contains("0"))
                            {

                            }
                            else
                            {
                                GameplayScreen.commandCounter++;
                                CommandQueue.addToCommandQueue(((commandCounter) + (". If the robot is ") + (String)IfStatementComboBox.SelectedValue + " " + IfTextEntry.Text + " squares away from an obstacle:"), commandQueueTextBlock
                                    , commandQueueScrollViewer);
                                Prompt.returnToGameplayFromPromptIfStatement(IfButton, PromptBack, PromptForward, null, confirmLabel, exitLabel, RedBlock, BlackOverlay, IfTitle, IfPrompt1st, IfPrompt2nd, IfStatementComboBox, IfTextEntry);
                                commandExecuted = "If Statement";
                                debugger.Text = commandExecuted;
                                IfButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/elsebutton.png", UriKind.Absolute
                                      ));
                                enableIfButtons();
                            }
                        }
                    }
                    catch (NullReferenceException)
                    {

                    }


                }

                //we don't want to change the command Executed back to null. needs to stay as "If Statement"

            }
            else if (commandExecuted.Equals("For Loop"))
            {
                double num;
                bool isNum = double.TryParse(ForTextEntry.Text, out num);
                if (isNum == true)
                {
                    if (ForTextEntry.Text.Equals("0") || ForTextEntry.Text.Equals("1"))
                    {
                    }
                    else
                    {
                        formarker = true;
                        GameplayScreen.commandCounter++;
                        CommandQueue.addToCommandQueue(((commandCounter) + (". For ") + ForTextEntry.Text + " iterations, do:"), commandQueueTextBlock, commandQueueScrollViewer);
                        CommandQueue.addToCommandQueue("[", commandQueueTextBlock, commandQueueScrollViewer);
                        Prompt.returnToGameplayFromForLoop(ForButton, PromptBack, PromptForward, commandExecuted, confirmLabel, exitLabel, RedBlock, BlackOverlay, ForTitle, ForPrompt1st, ForPrompt2nd, ForTextEntry);
                        ForButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/finishbutton.png", UriKind.Absolute
                              ));
                        enableForButtons();
                    }
                }
            }
            else if (commandExecuted.Equals("While Loop"))
            {
                double num;
                bool isNum = double.TryParse(WhileTextEntry.Text, out num);
                String check1 = (String)WhileLoopComboBox.SelectedValue;

                try
                {
                    bool check = check1.Equals(null);
                    if (isNum == true)
                    {
                        
                            GameplayScreen.commandCounter++;
                            CommandQueue.addToCommandQueue(((commandCounter) + (". While the robot is ") + (String)WhileLoopComboBox.SelectedValue + " " + WhileTextEntry.Text + " squares away from an obstacle:"), commandQueueTextBlock, commandQueueScrollViewer);
                            CommandQueue.addToCommandQueue("[", commandQueueTextBlock, commandQueueScrollViewer);
                            Prompt.returnToGameplayFromWhileLoop(WhileButton, PromptBack, PromptForward, commandExecuted, confirmLabel, exitLabel, RedBlock, BlackOverlay, WhileTitle, WhilePrompt1st, WhilePrompt2nd, WhileLoopComboBox, WhileTextEntry);
                            WhileButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/finishbutton.png", UriKind.Absolute
                              ));
                            enableWhileButtons();
                        
                    }
                }
                catch (NullReferenceException)
                {

                }
            }
        }

        private void disableAllButtons()
        {
            GoStraightButton.IsEnabled = false;
            TurnLeftButton.IsEnabled = false;
            TurnRightButton.IsEnabled = false;
            IfButton.IsEnabled = false;
            ForButton.IsEnabled = false;
            WhileButton.IsEnabled = false;
        }

        private void enableAllButtons()
        {
            GoStraightButton.IsEnabled = true;
            TurnLeftButton.IsEnabled = true;
            TurnRightButton.IsEnabled = true;
            IfButton.IsEnabled = true;
            ForButton.IsEnabled = true;
            WhileButton.IsEnabled = true;
        }

        private void enableIfButtons()
        {
            GoStraightButton.IsEnabled = true;
            TurnLeftButton.IsEnabled = true;
            TurnRightButton.IsEnabled = true;
            IfButton.IsEnabled = true;
            ForButton.IsEnabled = false;
            WhileButton.IsEnabled = false;
        }

        private void enableForButtons()
        {
            GoStraightButton.IsEnabled = true;
            TurnLeftButton.IsEnabled = true;
            TurnRightButton.IsEnabled = true;
            IfButton.IsEnabled = true;
            ForButton.IsEnabled = true;
            WhileButton.IsEnabled = false;
        }

        private void enableWhileButtons()
        {
            GoStraightButton.IsEnabled = true;
            TurnLeftButton.IsEnabled = true;
            TurnRightButton.IsEnabled = true;
            IfButton.IsEnabled = true;
            ForButton.IsEnabled = false;
            WhileButton.IsEnabled = true;
        }

        public static List<String> commandQueue = new List<String>();   
        public static String composite = "";

        private void PlayButtonImage_PointerPressed_1(object sender, PointerRoutedEventArgs e)
        {
            if (commandExecuted.Contains("Play") || formarker == true || whilemarker == true || elseMarker == true || commandExecuted.Contains("If Statement"))
            {

            }
            else if (commandQueue.Count != 0) //queue must not be empty, add a prompt at a later stage
            {

                commandExecuted = "Play";
                ButtonFlash.buttonFlash(PlayButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/playbuttoninverted.png", UriKind.Absolute), new Uri("ms-appx:///Assets/GameplayScreen/playbutton.png", UriKind.Absolute));
                Prompt.showBlackOverlay(BlackOverlay, width, height, offset);
                disableAllButtons();
                Prompt.showRedBlock(RedBlock, width, height, offset, TextPrompt, PromptBack, PromptForward, BackViewBox, ForwardViewBox, confirmLabel, exitLabel, StraightTextEntry);
            }
        }

        public static bool animationmarker;

        public static bool formarker = false; //true means a for loop is being used
        public static bool whilemarker = false; //true means a while loop is being used

        private void ForButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (formarker == true)
            {
                CommandQueue.addToCommandQueue("]", commandQueueTextBlock, commandQueueScrollViewer);
                formarker = false;
                ForButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/forbutton.png", UriKind.Absolute
                      ));
                enableAllButtons();
            }
            else
            {
                commandExecuted = "For Loop";
                ButtonFlash.buttonFlash(ForButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/forbuttoninverted.png", UriKind.Absolute),
            new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/forbutton.png"));
                formarker = true;
                startForPrompt();
                ForButton.IsEnabled = false;
                disableAllButtons();
            }
        }

        public void setCurrentTimerTicks()
        {
            ticks = timer.getTicks();
        }

        public static int getCurrentTimerTicks()
        {
            return ticks;
        }

        private void startForPrompt()
        {
            Prompt.showBlackOverlay(BlackOverlay, width, height, offset);
            Prompt.showRedBlockForLoop(RedBlock, PromptBack, PromptForward, BackViewBox, ForwardViewBox, confirmLabel, exitLabel, ForTitle, ForPrompt1st, ForPrompt2nd, ForTextEntry);
        }

        private void startWhilePrompt()
        {
            Prompt.showBlackOverlay(BlackOverlay, width, height, offset);
            Prompt.showRedBlockWhileLoop(RedBlock, PromptBack, PromptForward, BackViewBox, ForwardViewBox, confirmLabel, exitLabel, WhileTitle, WhilePrompt1st, WhilePrompt2nd, WhileTextEntry,WhileLoopComboBox);
        }

        private void WhileButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (whilemarker == true)
            {
                CommandQueue.addToCommandQueue("]", commandQueueTextBlock, commandQueueScrollViewer);
                whilemarker = false;
                WhileButtonImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/whilebutton.png", UriKind.Absolute
                      ));
                enableAllButtons();
            }
            else
            {
                commandExecuted = "While Loop";
                ButtonFlash.buttonFlash(WhileButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/whilebuttoninverted.png", UriKind.Absolute),
                new Uri("ms-appx:///Assets/GameplayScreen/ControlsButtons/whilebutton.png"));
                whilemarker = true;
                startWhilePrompt();
                WhileButton.IsEnabled = false;
                disableAllButtons();
            }
        }


        private void UndoButtonImage_PointerPressed_1(object sender, PointerRoutedEventArgs e)
        {
            if (commandExecuted.Equals("Play"))
            {

            }
            else if (commandQueue.Count != 0)
            {
                ButtonFlash.buttonFlash(UndoButtonImage, new Uri("ms-appx:///Assets/GameplayScreen/undobuttoninverted.png", UriKind.Absolute),
                    new Uri("ms-appx:///Assets/GameplayScreen/undobutton.png"));
                CommandQueue.removeLastEntryFromCommandQueue(commandQueueTextBlock);
                CommandQueue.updateCommandQueueTextBlock(commandQueueTextBlock, commandQueueScrollViewer);
            }
        }

        private async void TouchDevelopButton_PointerPressed_1(object sender, PointerRoutedEventArgs e)
        {
            //debug.Text = "Pointer Pressed";
            
            this.Frame.Navigate(typeof(TouchDevelopConversion));
            await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(1000));
            commandQueue.Clear();
            commandCounter = 0;
            PrepareToPlay.userHasHitObstacleOrWall = false;
            Prompt.returnToGameplayFromPrompt(PromptBack, PromptForward, commandExecuted, StraightTextEntry, confirmLabel, exitLabel, TextPrompt, width, height, offset, RedBlock, BlackOverlay, GoStraightButton);

        }

        private void TouchDevelopButton_PointerEntered_1(object sender, PointerRoutedEventArgs e)
        {
            debug.Text = "Pointer Entered";
            TouchDevelopButton.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/touchdevelopbuttonhighlighted.png", UriKind.Absolute
                     ));
        }

        private void TouchDevelopButton_PointerExited_1(object sender, PointerRoutedEventArgs e)
        {
            debug.Text = "Pointer Exited";
            TouchDevelopButton.Source = new BitmapImage(new Uri("ms-appx:///Assets/GameplayScreen/touchdevelopbutton.png", UriKind.Absolute
                     ));
        }

      

       

        
    }
}
